
package member

import (
    "time"
    "errors"
    "strings"
    "dhfshop/models"
	"github.com/astaxie/beego/orm"
)

// 积分记录
type IntegralLog struct {
	Id           int64     `orm:"column(id);pk;auto" json:"id" form:"id"` 
	PartnerId    int64       `orm:"column(partner_id);index" json:"partner_id" form:"partner_id"`
	MemberId     int64       `orm:"column(member_id)" json:"member_id" form:"member_id"`              /**/
	InOutType    int8      `orm:"column(in_out_type)" json:"in_out_type" form:"in_out_type"`        /*收支类型: 0支出,1收入*/
	BusinessKind int       `orm:"column(kind)" json:"kind" form:"kind"`                             /*业务类型*/
	OuterNo      string    `orm:"column(outer_no);size(256);null" json:"outer_no" form:"outer_no"`  // 外部单号 
	SrcIntegral  int       `orm:"column(src_integral)" json:"src_integral" form:"src_integral"`     /* 修改前积分值*/
	IncIntegral  int       `orm:"column(inc_integral)" json:"inc_integral" form:"inc_integral"`     /* 积分值变动量*/
	DstIntegral  int       `orm:"column(dst_integral)" json:"dst_integral" form:"dst_integral"`     /* 修改后积分值*/	
	Remark       string    `orm:"column(remark);size(256);null" json:"remark" form:"remark"`        //备注        
    CreatedAt    time.Time `orm:"auto_now_add;column(created_at);type(datetime)" json:"-" form:"-"`  //创建时间
}

func init() {
    orm.RegisterModel(new(IntegralLog))   
}

// 保存积分记录
func AddIntegralLog(v *IntegralLog) (id int64, err error) {
	o := models.GetDefaultDB()
	id, err = o.Insert(v)
	return
}

// 批量查询积分记录
func GetAllIntegralLogs(query map[string]string,fields []string,order_by map[string]string,offset int,limit int)([]*IntegralLog,int64,error){
	o := models.GetDefaultDB()
	qs := o.QueryTable(new(IntegralLog))
	for k, v := range query {
		k = strings.Replace(k, ".", "__", -1)
		if ok := strings.Contains(v, "|"); ok {
		    valueArr := strings.Split(v, "|")
			qs = qs.Filter(k, valueArr)
		}else{
		    qs = qs.Filter(k, v)
		}	
	}
	cnt, err := qs.Count()
	// order by:
	var sortFields []string
	for k, v := range order_by {
		orderby := ""
		if v == "desc" {
			orderby = "-" + k
		} else if v == "asc" {
			orderby = k
		} else {
			return nil, 0, errors.New("Error: Invalid order. Must be either [asc|desc]")
		}
		sortFields = append(sortFields, orderby)
	}
	qs = qs.OrderBy(sortFields...)
	var lists []*IntegralLog
	if _, err = qs.Limit(limit, offset).All(&lists, fields...); err == nil {
	   
		return lists, cnt, nil
	}
	return nil, 0, err
}

func GetIntegralLogByOuterNo(outerNo string) (logs *IntegralLog, err error) {
	o := models.GetDefaultDB()
	logs = &IntegralLog{InOutType: 0, OuterNo: outerNo}  
	if err = o.Read(logs, "InOutType", "OuterNo"); err != nil {
		return
	}
	return
}


		